import axios from 'axios'
import qs from 'qs'

//=>基础全局配置
axios.defaults.baseURL = 'http://localhost:8080'
axios.defaults.timeout = 10000
    //=> 携带cookies
axios.defaults.withCredentials = true
    //=> 将post请求格式化为 xx=xx&xxx=xxx
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.transformRequest = data => qs.stringify(data)

// token处理
axios.interceptors.request.use(config => {
    let token = localStorage.getItem('token')
    token && (config.headers.Authorization = token)
    return config
}, error => {
    return Promise.reject(error)
})

axios.interceptors.response.use(response => {
    return response.data;
}, error => {
    if (error.response) {
        switch (error.response) {
            // 错误状态码处理
            case '404':
                console.log('找不到借口')
                break
        }
    } else {
        if (!window.navigator.onLine) {
            // 断网处理
            alert("无法连接网络")
            return
        }
        return Promise.reject(error)
    }
})

export default axios